<template>
    <a-modal
        :title="title"
        centered
        :width="980"
        :maskClosable="false"
        :destroyOnClose="true"
        :visible="visible"
        :confirmLoading="confirmLoading"
        @ok="handleSubmit"
        @cancel="cancel"
    >
        <a-spin :spinning="confirmLoading">
            <a-form :model="form" ref="formRef" :rules="formRules">
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-item
                            label="机构名称"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            has-feedback
                            name="name"
                            :rules="[{ required: true, message: '请输入机构名称！' }]"
                        >
                            <a-input :maxLength="35" placeholder="请输入账号" v-model:value="form.name" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-item
                            label="唯一编码"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            has-feedback
                            name="code"
                            :rules="[{ required: true, message: '请输入唯一编码！' }]"
                        >
                            <a-input :maxLength="35" placeholder="请输入昵称" v-model:value="form.code" />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-item
                            label="上级机构"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            has-feedback
                            name="pid"
                            :rules="{ required: true, message: '请选择机构！' }"
                        >
                            <a-tree-select
                                placeholder="请选择机构"
                                v-model:value="form.pid"
                                style="width: 100%"
                                :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                                :treeData="treeData"
                                treeDefaultExpandAll
                                @change="initrOrgName"
                            >
                                <template #title="{ id }">
                                    <span>{{ id }}</span>
                                </template>
                            </a-tree-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-item
                            label="排序"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            has-feedback
                            name="sort"
                            :rules="[{ required: true, message: '请输入排序！' }]"
                        >
                            <a-input-number :min="0" :max="1000" placeholder="请输入排序" v-model:value="form.sort" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback name="remark">
                            <a-textarea :maxLength="100" placeholder="请输入备注" v-model:value="form.remark"> </a-textarea>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-spin>
    </a-modal>
</template>

<script lang='ts'>
import { defineComponent, PropType, reactive, toRefs, ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '@/store'
import { formRules } from '@/utils/validator'
import { RuleObject, ValidateErrorEntity } from 'ant-design-vue/es/form/interface'
import { getOrgList, sysOrgAdd, getOrgTree, sysOrgEdit } from '@/api/system/org'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { uniqueId } from 'lodash'
interface extIdsType {
    key: string
    orgId: unknown
    posId: unknown
}
export default defineComponent({
    name: 'orgFrom',
    components: {},
    props: {
        treeData: {
            type: Array,
            default: []
        },
        title: {
            type: String,
            default: ''
        }
    },
    emits: ['refresh'],
    setup(props, ctx) {
        const formRef = ref<any>(null)
        const router = useRouter()
        const store = useStore()
        const state = reactive({
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            },
            // 机构行样式
            labelCol_JG: {
                xs: { span: 24 },
                sm: { span: 3 }
            },
            wrapperCol_JG: {
                xs: { span: 24 },
                sm: { span: 20 }
            },
            count: 1,
            add: false,
            visible: false,
            confirmLoading: false,
            orgList: [] as any,
            posList: [],
            detailData: {} as any,
            sysEmpParamExtList: [],
            memberLoading: false,
            form: {
                name: '',
                code: '',
                pid: null,
                remark: '',
                sort: 100
                // account: '',
                // confirm: '',
                // name: '',
                // nickName: '',
                // birthday: '',
                // sex: 1,
                // sysEmpParam: {
                //   extIds: [] as extIdsType[],
                //   orgId: undefined,
                //   orgName: '',
                //   posIdList: [] as string[]
                // }
            },
            birthdayString: [] as string[]
        })
        /**详情监听 */
        watch(
            () => state.detailData,
            (v) => {
                var posIdList = [] as string[]
                var extIds = [] as extIdsType[]
                console.log(state.detailData)
                // v.sysEmpInfo.positions.map((item) => {
                //   posIdList.push(item.posId)
                // })
                // v.sysEmpInfo.extOrgPos.map((vv, i) => {
                //   extIds.push({
                //     key: uniqueId(),
                //     orgId: vv.orgId,
                //     posId: vv.posId
                //   })
                // })
                state.form = {
                    name: v.name,
                    code: v.code,
                    pid: v.pid,
                    remark: v.remark,
                    sort: v.sort,
                    id: v.id
                }

                // state.form = {
                //   account: v.account,
                //   name: v.name,
                //   nickName: v.nickName,
                //   confirm: '',
                //   password: '',
                //   phone: v.phone,
                //   sex: v.sex,
                //   email: v.email,
                //   birthday: v.birthday,
                //   sysEmpParam: {
                //     extIds: extIds,
                //     orgId: v.sysEmpInfo.orgId,
                //     orgName: v.sysEmpInfo.orgName,
                //     posIdList: posIdList
                //   }
                // }
            }
        )
        onMounted(() => {
            // sysOrgList().then((res) => {
            //   state.posList = res
            // })
            // getOrgTree().then((res) => {
            //     state.treeData2 = res
            // })
        })
        function handleSubmit() {
            state.confirmLoading = true
            console.log(props.title)
            if (props.title == '新增机构') {
                formRef.value
                    .validate()
                    .then(() => {
                        sysOrgAdd(state.form)
                            .then((res) => {
                                console.log(res)
                                message.success('新增成功')
                                state.confirmLoading = false
                                state.visible = false
                                ctx.emit('refresh')
                                // ctx.emit('getTree')
                                resetForm()
                            })
                            .catch((err) => {
                                state.confirmLoading = false
                            })
                    })
                    .catch((err) => {
                        state.confirmLoading = false
                        console.log('nopass', err)
                    })
            } else {
                formRef.value
                    .validate()
                    .then(() => {
                        sysOrgEdit(state.form)
                            .then((res) => {
                                message.success('编辑成功')
                                state.confirmLoading = false
                                state.visible = false
                                ctx.emit('refresh')
                                resetForm()
                            })
                            .catch((err) => {
                                state.confirmLoading = false
                            })
                    })
                    .catch((err) => {
                        state.confirmLoading = false
                        console.log('nopass', err)
                    })
            }
        }
        /**
         * 重置表单
         */
        function resetForm() {
            state.form = {
                account: '',
                name: '',
                nickName: '',
                confirm: '',
                password: '',
                phone: '',
                email: '',
                birthday: '',
                sex: 1,
                sysEmpParam: {
                    extIds: [] as extIdsType[],
                    orgId: undefined,
                    orgName: '',
                    posIdList: []
                }
            }
        }
        /**
         * 退出
         */
        const cancel = () => {
            resetForm()
            // formRef.value.resetFields()
            state.visible = false
            state.detailData = {}
        }
        /**
         * 禁用日期
         */
        const disabledDate = (current) => {
            return current && current > dayjs().endOf('day') //当天之前的不可选，包括当天
            // return current < dayjs().subtract(1, 'day')// 当天之前的不可选，不包括当天
        }

        /**
         * 增行
         */
        function newMember() {
            let data = state.form.sysEmpParam.extIds
            let length = data.length
            data.push({
                key: uniqueId(),
                orgId: undefined,
                posId: undefined
            })
        }
        /**
         * 删除
         */
        function remove(key) {
            state.form.sysEmpParam.extIds.splice(
                state.form.sysEmpParam.extIds.findIndex((v) => v.key == key),
                1
            )
        }
        /**
         * handleChange
         */
        function handleChange() {}
        /**
         * 选择树机构，初始化机构名称于表单中
         */
        function initrOrgName(value, label, extra) {
            console.log(extra)
            // console.log('vv', value, label, extra)
            state.form.pid = value
        }
        const validatePass = async (rule: RuleObject, value: string) => {
            if (value === '') {
                return Promise.reject('请输入密码')
            } else {
                if (state.form.confirm !== '') {
                    formRef.value.validateField('checkPass')
                }
                return Promise.resolve()
            }
        }
        const validatePass2 = async (rule: RuleObject, value: string) => {
            if (value === '') {
                return Promise.reject('请再次输入密码')
            } else if (value !== state.form.password) {
                return Promise.reject('请确认两次输入密码的一致性！')
            } else {
                return Promise.resolve()
            }
        }
        return {
            ...toRefs(state),
            props,
            formRef,
            formRules,
            handleSubmit,
            initrOrgName,
            validatePass,
            validatePass2,
            handleChange,
            disabledDate,
            cancel,
            remove,
            newMember
        }
    }
})
</script>
<style scoped lang="scss">
.ant-input-number {
    width: 100%;
}
</style>